<?php

namespace  App\Services;

use App\Http\Response\Helper;
use App\Notifications\EmailCode;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Notification;

class Email
{
    use Helper;

    public function sendCode($email)
    {
        Notification::route('mail', $email)
            ->notifyNow(new EmailCode());
    }

    /**
     * @param string                           $attribute
     * @param mixed                            $value
     * @param array                            $parameters
     * @param \Illuminate\Validation\Validator $validator
     *
     * @return bool
     */
    public function checkCode($attribute, $value, $parameters, $validator)
    {
        return Cache::pull('email_code:'.$parameters[0]) == $value;
    }

    /**
     * @param string $ip
     * @param string $email
     */
    public function checkThrottle($ip, $email)
    {
        if (Cache::get('throttle:email_code:'.$email)) {
            $this->error(70001);
        }

        if (Cache::get('throttle:email_code:'.$ip)) {
            $this->error(70001);
        }
    }

    /**
     * @param string $ip
     * @param string $email
     */
    public function setThrottle($ip, $email)
    {
        // 每个手机号30秒内只能发送一条短信验证码
        Cache::add('throttle:email_code:'.$email, 1, now()->addSeconds(30));
        // 每个 IP 30秒内只能发送一条短信验证码
        Cache::add('throttle:email_code:'.$ip, 1, now()->addSeconds(30));
    }
}
